package com.xfatm.simplebrowser.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.xfatm.simplebrowser.R;
import com.xfatm.simplebrowser.util.BeanManageUtils;
import com.xfatm.simplebrowser.util.HttpUtils;

/**
 * Created by wenjie on 2018/3/11.
 */

public class MainWebViewClient extends WebViewClient{
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        if(!HttpUtils.isSupportUrl(request.getUrl().toString())){
            Log.i("sout","打开自定义链接");
            try{
                Intent intent=new Intent(Intent.ACTION_VIEW,request.getUrl());
                view.getContext().startActivity(intent);
            }catch (Exception e){
                Log.i("sout","打开错误",e);
            }
            return true;
        }
        view.loadUrl(request.getUrl().toString(),request.getRequestHeaders());
        return false;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(!HttpUtils.isSupportUrl(url)){
            if(!HttpUtils.isSupportUrl(url.toString())){
                try{
                    Log.i("sout","打开自定义链接");
                    Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    view.getContext().startActivity(intent);
                }catch (Exception e){
                    Log.i("sout","打开错误",e);
                }
                return true;
            }
        }
        view.loadUrl(url,null);
        return false;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        Log.i("sout",url+"加载完成");
        //加载完页面后，将图标变为刷新
        if(!"go".equals(BeanManageUtils.getString("goButtonStatus"))){
            Button goButton=BeanManageUtils.getBean("goButton",Button.class);
            goButton.setText(R.string.refreshIcon);
            BeanManageUtils.saveBean("goButtonStatus","refresh");
        }
        //设置标题
        EditText et=BeanManageUtils.getBean(R.id.urlText,EditText.class);
        et.setText(BeanManageUtils.getBean("mainWebView",MainWebView.class).getTitle());
        super.onPageFinished(view, url);
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        Log.i("sout",url+"开始加载");
        BeanManageUtils.getBean(R.id.urlText, EditText.class).setText(url);

        //开始加载完页面，将图标变为取消
        Button goButton=BeanManageUtils.getBean("goButton",Button.class);
        goButton.setText(R.string.closeIcon);
        BeanManageUtils.saveBean("goButtonStatus","close");
        super.onPageStarted(view, url, favicon);
    }


}
